package com.application.viewmodel;

import android.app.Application;
import android.text.TextUtils;
import android.widget.Toast;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.application.bean.Student;
import com.application.util.MySQLiteOpenHelper;
import org.jetbrains.annotations.NotNull;

public class SQLiteInsertViewModel extends AndroidViewModel {
    public MutableLiveData<String> nameLiveData = new MutableLiveData<>();
    public MutableLiveData<String> numberLiveData = new MutableLiveData<>();
    public MutableLiveData<String> genderLiveData = new MutableLiveData<>();
    public MutableLiveData<String> scoreLiveData = new MutableLiveData<>();
    public final MutableLiveData<Boolean> clearInput = new MutableLiveData<>();
    private MySQLiteOpenHelper dbHelper;

    public SQLiteInsertViewModel(@NotNull Application application) {
        super(application);
        dbHelper = new MySQLiteOpenHelper(application);
    }

    public void setGenderToMale() {
        genderLiveData.setValue("男");
    }

    public void setGenderToFemale() {
        genderLiveData.setValue("女");
    }

    public void handleInsert() {
        String name = nameLiveData.getValue();
        String number = numberLiveData.getValue();
        String gender = genderLiveData.getValue();
        String score = scoreLiveData.getValue();

        if (TextUtils.isEmpty(gender)) {
            showToast("请选择性别");
            return;
        }
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(number) || TextUtils.isEmpty(score)) {
            showToast("请完善学生信息");
            return;
        }
        Student student = new Student(name, number, gender, score);
        long rowId = dbHelper.insertData(student);
        if (rowId == -2) {
            showToast("学号已存在");
        } else if (rowId != -1) {
            showToast("添加成功");
            clearInput.setValue(true);
        }  else {
            showToast("添加失败");
        }
    }

    private void showToast(String msg) {
        Toast.makeText(getApplication(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (dbHelper != null) {
            dbHelper.close();
        }
    }
}
